#include "WindowStatus.hpp"

WindowStatus::WindowStatus()
{
  // start polling right away
  TogglePolling(true);
}

WindowStatus::~WindowStatus()
{
  if (m_running)
    TogglePolling(false);
}

bool WindowStatus::TogglePolling(bool state)
{
  if (state && !m_running)
  {
    m_running = true;
    m_thread = ::CreateThread(NULL, 0, &WindowStatus::PollWindow, reinterpret_cast<void*>(this), 0, NULL);
    return true;
  }
  else if (!state && m_running)
  {
    m_running = false;
    ::WaitForSingleObject(m_thread, INFINITE);
    ::CloseHandle(m_thread);
    return true;
  }
  return false;
}

bool WindowStatus::IsRunning()
{
  return m_running;
}

void WindowStatus::SetCallback(WINDOWSTATUSCALLBACK callback)
{
  m_callback = callback;
}

WINDOWSTATUSCALLBACK WindowStatus::GetCallback()
{
  return m_callback;
}
  
unsigned long WindowStatus::PollWindows(void* param)
{
  WindowStatus* status = reinterpret_cast<WindowStatus*>(param);
  
  ::HWND lastWindow;
  unsigned long long lastTime;
  
  for (; status->IsRunning(); Sleep(POLLING_INTERVAL))
  {
    ::HWND currentWindow = GetForegroundWindow();
    if (currentWindow != lastWindow)
    {
      // pass to callback
      Timestamp* timestamp = new Timestamp(lastWindow, GetTickCount64() - timestamp);
      status->GetCallback()(timestamp);
      delete timestamp;
      
      lastWindow = currentWindow;
    }
  }
}